package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.TerminalInfoDao;
import com.framework.entity.flow.*;
import com.framework.entity.log.LogAccount;
import com.framework.entity.log.LogTranInfo;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.ter.*;
import com.framework.entity.tran.OrderNotice;
import com.framework.entity.tran.TranTransactionInfo;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.redis.util.RedisUtil;
import com.framework.service.*;
import com.framework.utils.DateUtils;
import com.framework.utils.excel.ExcelUtil;
import com.framework.utils.string.StringUtil;
import com.framework.validator.Assert;
import com.framework.view.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 终端业务层实现
 *
 * @author wq
 */
@Service("terminalInfoService")
@Transactional(rollbackFor = Exception.class)
public class TerminalInfoServiceImpl extends ServiceImpl<TerminalInfoDao, TerTerminalInfo> implements TerminalInfoService {

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private DistribuService distribuService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private TerminalTypeService terminalTypeService;
    @Autowired
    private NoticeReadService noticeReadService;
    @Autowired
    private TreeAgentService treeAgentService;
    @Autowired
    private OrderNoticeService orderNoticeService;
    @Autowired
    private TransactionInfoService transactionInfoService;

    @Autowired
    private FlowActivService flowActivService;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private FlowAccountService flowAccountService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LogTranInfoService logTranInfoService;

    @Autowired
    private TerFlowInfoService terFlowInfoService;

    @Autowired
    private TerInfoDetailService terInfoDetailService;

    @Autowired
    private ActiveService activeService;

    @Autowired
    private TerTerminalDueService terTerminalDueService;



    @Override
    public int queryActivationCount(Long agentId, Integer type, Integer isOwn) {
        if (type == null || type == 0 || agentId == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        int count = baseMapper.queryActivationCount(agentId, type, isOwn);
        return count;
    }

    @Override
    public TerTerminalInfo queryTerminalBySn(String sn) {
        if (StringUtils.isBlank(sn)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        TerTerminalInfo t = new TerTerminalInfo();
        t.setSn(sn);
        return baseMapper.selectOne(t);
    }

    @Override
    public Map<String, Object> queryOwnMap(String token, String sn) {
        Map<String, Object> map = new HashMap<>();
        TerTerminalInfo t = queryTerminalBySn(sn);
        Assert.isNull(t, "未查询到终端信息");
        TerminalOwnDto terminal = merchantService.queryMerchantOwnInfo(sn);
        map.put("terminal", terminal);
        //查询分配记录
        List<DisRecordDto> DisRecordList = distribuService.queryDisRecordList(sn);
        map.put("disRecordList", DisRecordList);
        return map;
    }

    @Override
    public Map<String, Object> queryTerminalList(String token, Integer pageNo, String startSn, String endSn, String model, Integer isActivation) {
        Map<String, Object> map = new HashMap<>();
        Assert.isBlank(token, "token不能为空");
        SysAgent agent = agentService.queryAgentByToken(token);
        //代理商id
        Long agentId = agent.getAgentId();
        if (pageNo != null) {
            pageNo = pageNo * 10;
        }
        //机具数量汇总
        TerminalSummaryDao summary = baseMapper.querySummarySum(agentId);
        map.put("summary", summary);
        List<TerTerminalInfo> list = baseMapper.queryTerminalList(agentId, pageNo, startSn, endSn, model, isActivation);
        map.put("list", list);
        map.put("total", list.size());
        return map;
    }

    @Override
    public Map<String, Object> queryTerminalTypeCountMap(String token, Integer isActivation) {
        Map<String, Object> map = new HashMap<>();
        Assert.isBlank(token, "token不能为空");
        SysAgent agent = agentService.queryAgentByToken(token);
        Long deptId = agent.getDeptId();
        Long agentId = agent.getAgentId();
        //查询渠道所属的终端类型
        List<TerTerminalType> list = terminalTypeService.queryTerminalTypeList(deptId);
        List<TerminalTypeDto> terminalList = new ArrayList<>();
        int totalCount = 0;
        //循环查询机具数据数量
        for (int i = 0; i < list.size(); i++) {
            TerminalTypeDto t = new TerminalTypeDto();
            //机具类型
            Integer type = list.get(i).getTerminalType();
            String name = list.get(i).getTerminalName();
            //String model = list.get(i).getModel();
            int count = baseMapper.queryTerByTypeCount(type, agentId, isActivation);
            t.setName(name); //终端名称
            t.setNumber(count);//终端数量
            t.setType(type);//终端类型
            terminalList.add(t);
            totalCount = count++;
        }
        map.put("terminalList", terminalList);
        map.put("totalCount", totalCount); //总数量
        return map;
    }

    @Override
    public List<TerTerminalInfo> queryTerminalByTypeList(Integer terminalType, String token, Integer isActivation) {
        if (terminalType == null || StringUtils.isBlank(token)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        return baseMapper.queryTerByTypeList(terminalType, agent.getAgentId(), isActivation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void disTerminal(String token, Long accept, String startSn, String endSn, String model, Integer isActivation) {
        if (accept == null ||
                StringUtils.isBlank(startSn) ||
                StringUtils.isBlank(endSn)
        ) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        if (agentId.intValue() == accept.intValue()) {
            throw new RRException("9999", "不可以分配给自己");
        }
        //校验接收人是否是自己名下代理
        boolean isOwn = treeAgentService.isAgentOwn(agentId, accept);
        if (isOwn == false) {
            throw new RRException("9999", "选择的代理商不在您的名下");
        }
        //生成唯一编号
        String noticeTerNo = StringUtil.getDateString(4);
        //校验是否有激活或者禁用的终端号
        List<TerTerminalInfo> list = baseMapper.queryTerminalList(agentId, null, startSn, endSn, model, isActivation);
        if (list.size() == 0) {
            throw new RRException("9999", "未查询到终端信息");
        }
        for (TerTerminalInfo info : list) {
            Integer IsActivation = info.getIsActivation();
            String sn = info.getSn();
            if (IsActivation.intValue() == 2 || IsActivation.intValue() == 3) {
                throw new RRException("9999", "终端(" + sn + ")已经激活或者禁用");
            }
            //分配终端信息
            TerDistribu d = distribuService.queryDistribu(sn, agentId);
            if (d == null) {
                throw new RRException("9999", "终端(" + sn + ")不在您的名下");
            }
            //增加和修改分配记录
            distribuService.insertDistribu(sn, agentId, accept);
            //添加终端分配通知列表
            FlowNoticeTerInfo f = new FlowNoticeTerInfo();
            f.setCreateTime(new Date());
            f.setNoticeTerNo(noticeTerNo);
            f.setSn(sn);
            noticeReadService.insertNoticeTerInfo(f);
        }
        //添加终端分配通知基础信息
        FlowNoticeTer ter = new FlowNoticeTer();
        ter.setNoticeTerNo(noticeTerNo);
        ter.setCreateDate(new Date());
        ter.setDisAgentId(agentId);
        ter.setAcceptAgentId(accept);
        ter.setEndSn(endSn);
        ter.setIsAccept(1);
        ter.setIsRead(1);
        ter.setStartSn(startSn);
        ter.setTerNumber(list.size());
        noticeReadService.insertNoticeTer(ter);
    }

    @Override
    public void updateTerminal(TerTerminalInfo terminal) {
        if (terminal == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        String sn = terminal.getSn();
        if (StringUtils.isBlank(sn)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        baseMapper.updateTerminal(terminal);
    }

    @Override
    public List<PurchaserView> queryActivList(Integer terminalType, Long deptId, BigDecimal activAmount) {
        return baseMapper.queryActivList(terminalType, deptId, activAmount);
    }

    @Override
    public TerTerminalInfo queryTerminalByMCode(String MCode) {
        if (StringUtils.isBlank(MCode)) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        TerTerminalInfo t = new TerTerminalInfo();
        t.setMerchantCode(MCode);
        return baseMapper.selectOne(t);
    }

    @Override
    public List<TerTerminalInfo> queryTerListByNo(Map<String, Object> params) {
        //判断是否为纯数字，是,则mybatis中需要用${}
        if (params.get("startNo") != null && params.get("endNo") != null) {
            if (StringUtil.isNumeric(params.get("startNo").toString()) && StringUtil.isNumeric(params.get("endNo").toString())) {
                params.put("numSign", "Yes");
            } else {
                params.put("numSign", "No");
            }
        }

        return baseMapper.queryTerListByNo(params);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleTer(List<TerTerminalInfo> list, Long agentId, BigDecimal reapAmount, Long isOnline, String startSn, String endSn, Long orderId, Long deptId, Date activDate) {
        if (list.size() == 0) {
            throw new RRException("9999", "未查询到终端信息");
        }
        //生成唯一编号
        String noticeTerNo = StringUtil.getDateString(4);

        SysAgent agent = agentService.queryBasicAgentBydeptId(deptId);
        for (TerTerminalInfo terTerminalInfo : list) {

            Integer IsActivation = terTerminalInfo.getIsActivation();
            String sn = terTerminalInfo.getSn();
            if (IsActivation.intValue() == 2 || IsActivation.intValue() == 3) {
                throw new RRException("9999", "终端(" + sn + ")已经激活或者禁用");
            }
            terTerminalInfo.setPurchaserId(agentId);
            terTerminalInfo.setReapAmount(reapAmount);
            terTerminalInfo.setIsOnLine(isOnline);
            terTerminalInfo.setActivDueTime(activDate);
            this.baseMapper.updateById(terTerminalInfo);
            terFlowInfoService.addDistribuInfo(sn, deptId);
            //添加终端分配通知列表
            FlowNoticeTerInfo f = new FlowNoticeTerInfo();
            f.setCreateTime(new Date());
            f.setNoticeTerNo(noticeTerNo);
            f.setSn(sn);
            noticeReadService.insertNoticeTerInfo(f);
        }
        //添加记录
        FlowNoticeTer ter = new FlowNoticeTer();
        ter.setNoticeTerNo(noticeTerNo);
        ter.setCreateDate(new Date());
        ter.setDisAgentId(agent.getAgentId());
        ter.setAcceptAgentId(agentId);
        ter.setEndSn(endSn);
        ter.setIsAccept(1);
        ter.setIsRead(1);
        ter.setStartSn(startSn);
        ter.setTerNumber(list.size());
        //添加关系记录
        noticeReadService.insertNoticeTer(ter);
        OrderNotice orderNotice = new OrderNotice();
        orderNotice.setOrderId(orderId);
        orderNotice.setNoticeTerNo(noticeTerNo);
        orderNoticeService.insertOrderNotice(orderNotice);

    }

    @Override
    public Integer updateTerminalInfoForLeShua(String fileName, MultipartFile file) {


        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }
        Integer count = 0;
        Row row;
        boolean flag;
        BigDecimal totalAmount = new BigDecimal("0.00");
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            //sn
            String sn = row.getCell(0).getStringCellValue().trim();
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            //获取merchantCode
            String merchantCode = row.getCell(1).getStringCellValue().trim();
            //交易额
            BigDecimal money = new BigDecimal(row.getCell(2).getStringCellValue().trim());

            int terminalType = Integer.valueOf(row.getCell(3).getStringCellValue().trim());

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = dateFormat.parse(row.getCell(4).getStringCellValue().trim());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String isVipstr = row.getCell(5).getStringCellValue().trim();

            TerTerminalInfo t = queryTerminalBySn(sn);
            //有此机具
            if (t != null) {
                //如果商户号不同则修改商户号
                if (merchantCode != null && !"".equals(merchantCode)) {
                    if (!t.getMerchantCode().equals(merchantCode)) {
                        t.setMerchantCode(merchantCode);
                        baseMapper.updateTerminalForLeShua(t);
                    }
                }
                totalAmount = totalAmount.add(money);
                //导入交易
                TranTransactionInfo info = new TranTransactionInfo();
                info.setTerminalType(terminalType);
                info.setTransactionDate(date);
                info.setAmount(money);
                info.setDeptId(t.getDeptId());
                info.setCreateDate(new Date());
                info.setSn(sn);
                info.setMerchantCode(merchantCode);
                info.setIsVip(isVipstr);
                flag = transactionInfoService.insert(info);
                count += (flag ? 1 : 0);
            }
        }
        List<LogAccount> logAccounts = transactionInfoService.queryTerAccountList(5);

        LogAccount logAccount = logAccounts.get(0);

        LogTranInfo logTranInfo = new LogTranInfo();
        logTranInfo.setAccountId(logAccount.getAccountId());
        logTranInfo.setLogStates("SUCCESS");
        logTranInfo.setExplainsInfo(logAccount.getExpInfo() + "-导入成功");
        logTranInfo.setCreateDate(new Date());
        logTranInfo.setTotalNumber(count);
        logTranInfo.setTotalTransaction(totalAmount);
        logTranInfoService.insert(logTranInfo);

        return count;
    }

    @Override
    public PageUtils queryTerminalListByAdmin(Map<String, Object> params) {
        //判断是否为纯数字，是,则mybatis中需要用${}

        if (params.get("startSn") != null && params.get("endSn") != null) {
            if (StringUtil.isNumeric(params.get("startSn").toString()) && StringUtil.isNumeric(params.get("endSn").toString())) {
                params.put("numSign", "Yes");
            } else {
                params.put("numSign", "No");
            }
        }
        Integer currPage = Integer.valueOf(params.get("page").toString());
        Integer pageSize = Integer.valueOf(params.get("limit").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        List<Map<String, Object>> terlist = this.baseMapper.queryTerminalListByAdmin(params);
        Integer totalCount = this.baseMapper.queryTerminalCountByAdmin(params);
        //放入redis,以下载
        redisUtil.set("params", params, 60 * 5);
        return new PageUtils(terlist, totalCount, pageSize, currPage);
    }

    @Override
    public TerTerminalInfo queryTerminalById(Long terminalId) {
        TerTerminalInfo terminalInfo = this.baseMapper.queryTerminalById(terminalId);
        return terminalInfo;
    }

    @Override
    public void downExcel(HttpServletResponse response) {
        //从redis中获取条件用于再次查询
        Map<String, Object> newParams = (Map<String, Object>) redisUtil.get("params");

        if (CollectionUtils.isEmpty(newParams)) {
            throw new RRException("9000", "请重新查询");
        }
        //去除分页条件
        newParams.remove("limit");
        newParams.remove("start");
        //结果
        List<Map<String, Object>> terlist = this.baseMapper.queryTerminalListByAdmin(newParams);

        String[] title = {"终端号", "商户号", "机具型号", "机具名称", "激活状态", "激活时间", "是否线上", "是否报备", "返现人推荐码", "返现人姓名", "返现人手机", "返现金额"};
        String fileName = "终端信息表" + System.currentTimeMillis() + ".xlsx";


        String[][] content = new String[terlist.size()][];
        for (int i = 0; i < terlist.size(); i++) {
            content[i] = new String[title.length];
            Map<String, Object> obj = terlist.get(i);
            //终端号
            content[i][0] = obj.get("sn").toString();
            //商户号
            content[i][1] = obj.get("merchantCode").toString();
            //机具类型
            content[i][2] = obj.get("model").toString();
            //终端类型
            content[i][3] = obj.get("terminalName").toString();
            //是否激活
            Integer isActivation = Integer.valueOf(obj.get("isActivation").toString());
            String isActive = isActivation == 1 ? "未激活" : (isActivation == 2 ? "已激活" : "禁用");
            content[i][4] = isActive;
            //激活时间
            content[i][5] = obj.get("activationDate") == null ? "未激活" : obj.get("activationDate").toString();
            Integer isOnline = Integer.valueOf(obj.get("isOnline").toString());
            String isOnlineStr = isOnline == 1 ? "是" : "否";
            //是否线上
            content[i][6] = isOnlineStr;
            Integer isReport = Integer.valueOf(obj.get("isReport").toString());
            String isReportStr = isReport == 2 ? "是" : "否";
            //是否报备
            content[i][7] = isReportStr;
            //返现人id,推荐码
            content[i][8] = obj.get("agentId") == null ? "无返现人" : obj.get("agentId").toString();
            //姓名
            content[i][9] = obj.get("name") == null ? "无返现人" : obj.get("name").toString();
            //手机号码
            content[i][10] = obj.get("phone") == null ? "无返现人" : obj.get("phone").toString();
            //返现金额
            content[i][11] = obj.get("reapAmount") == null ? "0.00" : obj.get("reapAmount").toString();

        }
        String sheetName = "终端信息表";

        Workbook workbook = ExcelUtil.generateNewWorkbook(sheetName, title, content);

        ExcelUtil.downLoadByExcel(response, fileName, workbook);

    }

    @Override
    public Integer importTerminal(String fileName, MultipartFile file, Long deptId) {

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "未获取到信息页");
        }
        Row row;
        List<TerTerminalInfo> terlist = new ArrayList<>();
        //用于新增
        TerTerminalInfo terTerminalInfo;
        //接收查询
        TerTerminalInfo t2;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            //获取表格中的数据
            String sn = row.getCell(0).getStringCellValue();
            String merchantCode = row.getCell(1).getStringCellValue();
            String terminalType = row.getCell(2).getStringCellValue();
            String model = row.getCell(3).getStringCellValue();
            if (sn == null || "".equals(sn)) {
                throw new RRException("9000", "未获取到终端号");
            }
            if (merchantCode == null || "".equals(merchantCode)) {
                throw new RRException("9000", "未获取到商户号");
            }
            if (terminalType == null || "".equals(terminalType)) {
                throw new RRException("9000", "未获取到终端类型");
            }
            if (model == null || "".equals(model)) {
                throw new RRException("9000", "未获取到终端型号");
            }
            //查询终端
            t2 = this.queryTerminalBySn(sn);
            //没有则新增
            if (t2 == null) {
                terTerminalInfo = new TerTerminalInfo();
                terTerminalInfo.setSn(sn);
                terTerminalInfo.setMerchantCode(merchantCode);
                terTerminalInfo.setModel(model);
                terTerminalInfo.setTerminalType(Integer.valueOf(terminalType));
                terTerminalInfo.setDeptId(deptId);
                terlist.add(terTerminalInfo);
            }

        }
        Integer count;
        if(terlist.size()>0){
            try {
                count = baseMapper.insertList(terlist);
                SysAgent agent = agentService.queryBasicAgentBydeptId(deptId);
                distribuService.insertDisList(terlist, agent.getAgentId());
            } catch (Exception e) {
                e.printStackTrace();
                throw new RRException("9000", e.getMessage());
            }
        }else {
            throw new RRException("9000","表中终端已存在,请勿重复导入");
        }

        return count;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void rebackTerminal(Map<String, Object> q) {
        List<TerTerminalInfo> list = this.queryTerListByNo(q);

        if (list == null || list.size() == 0) {
            throw new RRException("9000", "未查询到终端信息");
        }
        if (q.get("name") == null && q.get("phone") == null && q.get("agentId") == null) {
            SysAgent agent = agentService.queryBasicAgentBydeptId(Long.valueOf(q.get("deptId").toString()));
            q.put("agentId", agent.getAgentId());
        }
        ;
        TerDistribu dis;
        for (TerTerminalInfo terTerminalInfo : list) {

            dis = distribuService.queryDistribuByAgentId(terTerminalInfo.getSn(), Long.valueOf(q.get("agentId").toString()));
            if (dis == null) {
                throw new RRException("9000", "该机器不属于该合伙人,无法回拨");
            }

            distribuService.rebackTerminal(terTerminalInfo.getSn(), dis.getToAid());
            dis.setState(2);
            dis.setReceiveState(2);
            dis.setToAid(null);
            distribuService.updateAllColumnById(dis);
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void distribuTer(Map<String, Object> q) {
        List<TerTerminalInfo> list = queryTerListByNo(q);
        if (list == null || list.size() == 0) {
            throw new RRException("9000", "未查询到终端信息");
        }
        boolean isOnline = (boolean) q.get("isOnline");
        boolean isActiver = (boolean) q.get("isActiver");
        BigDecimal reapAmount=q.get("amount")!=null?new BigDecimal(q.get("amount").toString()):new BigDecimal("0.00");

        Long agentId=Long.valueOf(q.get("agentId").toString());

        Long deptId=Long.valueOf(q.get("deptId").toString());
        SysAgent agent = agentService.queryBasicAgentBydeptId(deptId);
        for (TerTerminalInfo terTerminalInfo : list) {
            terTerminalInfo.setIsOnLine(isOnline ? 1L : 0L);
            if (isActiver) {
                terTerminalInfo.setPurchaserId(agentId);
                terTerminalInfo.setReapAmount(reapAmount);
            }
            distribuService.disTerminal(terTerminalInfo.getSn(),agentId,deptId);
            baseMapper.updateById(terTerminalInfo);
            terFlowInfoService.addDistribuInfo(terTerminalInfo.getSn(), terTerminalInfo.getDeptId());

        }
        //生成唯一编号
        String noticeTerNo = StringUtil.getDateString(4);
        //添加终端分配通知基础信息
        FlowNoticeTer ter = new FlowNoticeTer();
        ter.setNoticeTerNo(noticeTerNo);
        ter.setCreateDate(new Date());
        ter.setDisAgentId(agent.getAgentId());
        ter.setAcceptAgentId(Long.valueOf(q.get("agentId").toString()));
        ter.setEndSn(q.get("endNo").toString());
        ter.setIsAccept(1);
        ter.setIsRead(1);
        ter.setStartSn(q.get("startNo").toString());
        ter.setTerNumber(list.size());
        noticeReadService.insertNoticeTer(ter);
        if(deptId.equals(889326L)){
            Date dueDate=DateUtils.stringToDate(q.get("activDueTime").toString(),DateUtils.DATE_PATTERN);
            BigDecimal dueAmount=new BigDecimal(q.get("dueAmount").toString());
            terTerminalDueService.addTerminalDueList(list,isOnline?1L:0L,reapAmount,dueDate,dueAmount,deptId);
        }



    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer reportOnline(String fileName, MultipartFile file, Long deptId) {

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "未获取到信息页");
        }

        Row row;
        TerTerminalInfo terminalInfo;
        Integer count = 0;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            //终端号
            String sn = row.getCell(0).getStringCellValue();
            //姓名
            String name = row.getCell(1).getStringCellValue();
            //手机号码
            String phone = row.getCell(2).getStringCellValue();
            //返现金额
            BigDecimal reapAmount = new BigDecimal(row.getCell(3).getStringCellValue());

            Long agentId = agentService.checkParent(phone, name, deptId);
            terminalInfo = new TerTerminalInfo();
            terminalInfo.setSn(sn);
            terminalInfo.setDeptId(deptId);
            terminalInfo = baseMapper.selectOne(terminalInfo);
            if (terminalInfo == null) {
                throw new RRException("9000", "无终端" + sn + "的信息");
            }
            terminalInfo.setIsOnLine(1L);
            terminalInfo.setReapAmount(reapAmount);
            terminalInfo.setPurchaserId(agentId);
            count += baseMapper.updateById(terminalInfo);

        }

        return count;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer excelReback(String fileName, MultipartFile file, Long deptId) {

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "未获取到信息页");
        }
        Row row;
        TerDistribu dis;
        Integer count = 0;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            //终端号
            String sn = row.getCell(0).getStringCellValue();
            //回拨目标姓名
            String name = row.getCell(1).getStringCellValue();
            //回拨目标手机号码
            String phone = row.getCell(2).getStringCellValue();

            Long agentId = agentService.checkParent(phone, name, deptId);

            dis = distribuService.queryDistribuByAgentId(sn, agentId);
            if (dis == null) {
                throw new RRException("9000", "机具:" + sn + "不属于合伙人：" + name + "，无法回拨");
            }

            distribuService.rebackTerminal(sn, dis.getToAid());
            dis = distribuService.queryDistribuByAgentId(sn, agentId);

            dis.setState(2);
            dis.setReceiveState(2);
            dis.setToAid(null);
            //回拨成功则+1
            if (distribuService.updateAllColumnById(dis)) {
                count++;
            }
        }

        return count;
    }


    @Override
    public void unReportTerminal(String sn) {
        TerTerminalInfo t = queryTerminalBySn(sn);
        t.setIsReport(1L);
        updateById(t);
    }

    @Override
    public Map<String, Object> bindSnAndTerminalCode(String merc_id,
                                                     String merc_nm,
                                                     String corg_merc_id,
                                                     String bind_dt,
                                                     String sn_no,
                                                     String org_no,
                                                     String trm_no) {
        Map<String, Object> result = new HashMap<>();


        if (!"1467".equals(org_no)) {
            result.put("RspCode ", "000000");
            result.put("RspDes", "机构号不一致");
            return result;
        }


        TerTerminalInfo t = queryTerminalBySn(sn_no);
        if (t == null) {
            result.put("RspCode ", "000000");
            result.put("RspDes", "无此终端");
            return result;
        }
        t.setMerchantCode(trm_no);
        System.out.println("----修改了SP:" + t.getSn() + "的终端号为:" + t.getMerchantCode() + "---");
        baseMapper.updateById(t);
        result.put("RspCode ", "000000");
        result.put("RspDes", "绑定成功");
        return result;
    }

    @Override
    public Integer updateMer(String fileName, MultipartFile file) {

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }
        Integer count = 0;
        Row row;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //sn
            String sn = row.getCell(0).getStringCellValue().trim();
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            //获取merchantCode
            String merchantCode = row.getCell(1).getStringCellValue().trim();

            TerTerminalInfo t = queryTerminalBySn(sn);
            //有此机具
            if (t != null) {
                t.setMerchantCode(merchantCode);
                count += baseMapper.updateById(t);
            }
        }

        return count;
    }

    @Override
    public Map<String, Object> uploadToActiv(String fileName, MultipartFile file) {

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);

        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }
        Integer reapCount = 0;
        Integer activCount = 0;
        Row row;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            String sn = row.getCell(0).getStringCellValue().trim();
            //验证机器信息
            TerTerminalInfo info = queryTerminalBySn(sn);
            if (info == null) {
                continue;
            }
            //验证是否是考拉
            if (!info.getDeptId().equals(889326L)) {
                continue;
            }
            //是否已激活
            FlowActiv flowActiv = flowActivService.queryActivBySn(sn);
            if (flowActiv != null && info.getIsActivation().intValue() == 2) {
                continue;
            }


            activCount++;
            if (info.getIsOnLine().intValue() == 1) {

                List<TranTransactionInfo> list = transactionInfoService.selectList(new EntityWrapper<TranTransactionInfo>().eq("sn", info.getSn()));

                BigDecimal result = list.stream()
                        .filter(e -> e.getAmount() != null)
                        .map(TranTransactionInfo::getAmount)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                //修改账户余额
                agentInfoService.addAmount(info.getPurchaserId(), info.getReapAmount());
                //添加激活返现信息
                String activIdSn = StringUtil.getDateString(6);
                FlowActiv f = new FlowActiv();
                f.setAgentId(info.getPurchaserId());
                f.setCreateTime(new Date());
                f.setSn(sn);
                f.setAmount(info.getReapAmount());
                f.setPartAmount(result);
                f.setActivDate(new Date());
                f.setActivId(activIdSn);
                flowActivService.insert(f);
                //添加流水日志
                FlowAccount account = new FlowAccount();
                account.setCreateTime(new Date());
                account.setAccountType(5);
                account.setBelId(activIdSn);
                account.setSupportType(2);
                account.setAmount(info.getReapAmount());
                account.setAgentId(info.getPurchaserId());
                flowAccountService.insertFlowAccount(account);
                reapCount++;
            }
            activTerminal(info.getSn());

        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("reapCount", reapCount);
        result.put("activCount", activCount);
        return result;
    }

    @Override
    public Map<String, Object> queryTerminalListByToken(String token, String startSn, String endSn, Integer terminalType, Integer isActivation, Integer type) {
        SysAgent agent = agentService.queryAgentByToken(token);

        Map<String, Object> params = new HashMap<>(8);
        boolean empty1 = StringUtil.isEmpty(startSn);
        boolean empty2 = StringUtil.isEmpty(endSn);
        if (!empty1 && !empty2) {
            if (StringUtil.isNumeric(startSn) && StringUtil.isNumeric(endSn)) {
                params.put("numSign", "Yes");
            } else {
                params.put("numSign", "No");
            }
        }

        params.put("agentId", agent.getAgentId());
        params.put("startSn", startSn);
        params.put("endSn", endSn);
        params.put("terminalType", terminalType);
        params.put("isActivation", isActivation);
        params.put("type", type);
        params.put("deptId", agent.getDeptId());
        List<TerManagementBean> list = baseMapper.queryTerminalListByAgent(params);

        Map<String, Object> result = new HashMap<>(2);
        result.put("list", list);
        result.put("count", list.size());
        return result;
    }

    @Override
    public List<Map<String, Object>> queryTerminalOwner(String token, String[] snList) {
        SysAgent agent = agentService.queryAgentByToken(token);
        if (snList == null || snList.length == 0) {
            return new ArrayList<>();
        }
        return baseMapper.queryTerminalOwner(agent.getDeptId(), snList);
    }

    @Override
    public Map<String, Object> queryFlowInfoBySn(String token, String sn) {

        SysAgent sysAgent = agentService.queryAgentByToken(token);
        SysAgent basicAgent = agentService.queryBasicAgentBydeptId(sysAgent.getDeptId());
        Long agentId = distribuService.queryTerminalOwn(sn);
        if (!sysAgent.getAgentId().equals(basicAgent.getAgentId())) {
            SysAgent topAgent = agentService.queryTopAgentBySubIdAndBase(sysAgent.getAgentId(), basicAgent.getAgentId());
            if (topAgent == null) {
                throw new RRException("9000", "未查到顶级客户经理");
            }
            SysAgent topAgentSnOwner = agentService.queryTopAgentBySubIdAndBase(agentId, basicAgent.getAgentId());
            if (topAgent == null) {
                throw new RRException("9000", "未查到终端所属人客户经理");
            }
            if (!topAgent.getAgentId().equals(topAgentSnOwner.getAgentId())) {
                throw new RRException("9000", "该机器不输入您的团队,无法查看");
            }
        }
        TerFlowInfo terFlowInfo = terFlowInfoService.selectOne(new EntityWrapper<TerFlowInfo>()
                .eq("sn", sn)
                .eq("dept_id", sysAgent.getDeptId())
        );

        if (terFlowInfo == null) {
            Long infoId = terFlowInfoService.getInfoId(sn, sysAgent.getDeptId());
            terFlowInfoService.addDistribuInfo(sn, sysAgent.getDeptId());
            terFlowInfo = new TerFlowInfo();
            terFlowInfo.setInfoId(infoId);
        }

        List<TerInfoDetail> terInfoDetails = terInfoDetailService.selectList(new EntityWrapper<TerInfoDetail>().eq("info_id", terFlowInfo.getInfoId())
                .orderBy("create_time", false)
        );
        terInfoDetails.stream().forEach(e -> e.setShowTime(DateUtils.format(e.getCreateTime(), DateUtils.DATE_TIME_PATTERN)));

        TerTerminalInfo terminalInfo = queryTerminalBySn(sn);
        TerMerchantReport report = merchantService.queryMerchantBySn(sn);
        if (terminalInfo == null) {
            throw new RRException("9000", "未查询到该机具");
        }

        Map<String, Object> result = new HashMap<>(3);

        result.put("list", terInfoDetails);
        result.put("activationDate", terminalInfo.getIsActivation() == 1 ? "未激活" : DateUtils.format(terminalInfo.getActivationDate(), DateUtils.DATE_PATTERN));
        result.put("reportDate", report == null ? "未报备" : DateUtils.format(report.getCreateDate(), DateUtils.DATE_PATTERN));
        return result;

    }

    @Override
    public Integer queryLastMonthActivCount(Long agentId, String date) {
        return baseMapper.queryLastMonthActivCount(agentId, date);
    }


    @Override
    public void activTerminal(String sn) {
        TerTerminalInfo t = new TerTerminalInfo();
        t.setSn(sn);
        t.setIsActivation(2);
        t.setActivationDate(new Date());
        updateTerminal(t);

    }

    @Override
    public int queryTLCount(Long agentId) {
        return baseMapper.queryTLCount(agentId);
    }


    @Override
    public Map<String, Object> uploadToActivTL(String fileName, MultipartFile file) {


        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }
        Integer reapCount = 0;
        Integer activCount = 0;
        Row row;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            String merchantCode = row.getCell(0).getStringCellValue().trim();
            //查询机器
            TerTerminalInfo info = queryTerminalByMCode(merchantCode);
            if (info == null) {
                continue;
            }
            TerMerchantReport report = merchantService.queryMerchantBySn(info.getSn());
            if (info.getIsReport().intValue() != 2 && report == null) {
                continue;
            }
            //验证渠道，非星脉的跳过
            if (!info.getDeptId().equals(5L)) {
                continue;
            }
            //已激活跳过
            if (info.getIsActivation().intValue() == 2) {
                continue;
            }

            activCount++;

            List<TranTransactionInfo> list = transactionInfoService.selectList(new EntityWrapper<TranTransactionInfo>().eq("sn", info.getSn()));
            BigDecimal result = list.stream()
                    .filter(e -> e.getAmount() != null)
                    .map(TranTransactionInfo::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            PurchaserView purchaserView = new PurchaserView();
            purchaserView.setIsOnline(info.getIsOnLine().intValue());
            purchaserView.setIsReport(info.getIsReport().intValue());
            purchaserView.setSn(info.getSn());
            purchaserView.setReapAmount(info.getReapAmount());
            purchaserView.setPartAmount(result);
            purchaserView.setPurchaserId(info.getPurchaserId());

            //处理是否是本人激活
            if (activeService.handleTlActiv(purchaserView, info.getDeptId())) {
                continue;
            }

            //线上则返现
            if (info.getIsOnLine().intValue() == 1) {

                if(info.getPurchaserId()!=null && info.getReapAmount()!=null){
                    //修改账户余额
                    agentInfoService.addAmount(info.getPurchaserId(), info.getReapAmount());
                    //添加激活返现信息
                    String activIdSn = StringUtil.getDateString(6);
                    FlowActiv f = new FlowActiv();
                    f.setAgentId(info.getPurchaserId());
                    f.setCreateTime(new Date());
                    f.setSn(info.getSn());
                    f.setAmount(info.getReapAmount());
                    f.setPartAmount(result);
                    f.setActivDate(new Date());
                    f.setActivId(activIdSn);
                    flowActivService.insert(f);
                    //添加流水日志
                    FlowAccount account = new FlowAccount();
                    account.setCreateTime(new Date());
                    account.setAccountType(5);
                    account.setBelId(activIdSn);
                    account.setSupportType(2);
                    account.setAmount(info.getReapAmount());
                    account.setAgentId(info.getPurchaserId());
                    flowAccountService.insertFlowAccount(account);
                    reapCount++;
                }
            }
            //修改终端信息
            activTerminal(info.getSn());

        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("reapCount", reapCount);
        result.put("activCount", activCount);

        return result;
    }

    @Override
    public Integer updateMerForTL(String fileName, MultipartFile file) {

        Sheet sheet = ExcelUtil.getSheetFromFile(fileName, file, 0);

        if (sheet == null) {
            throw new RRException("9000", "系统异常");
        }
        Integer count = 0;
        Row row;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //sn
            String sn = row.getCell(0).getStringCellValue().trim();
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            //获取merchantCode
            String merchantCode = row.getCell(1).getStringCellValue().trim();

            //先验证商户号是否绑定过旧机器
            TerTerminalInfo terminalInfo = queryTerminalByMCode(merchantCode);
            //已绑定则不修改
            if (terminalInfo != null) {
                continue;
            }
            //无则修改
            TerTerminalInfo info = queryTerminalBySn(sn);
            if (info != null) {
                info.setMerchantCode(merchantCode);
                count += baseMapper.updateById(info);
            }
        }
        return count;
    }

    @Override
    public Integer uploadToActivXY(String fileName, MultipartFile file) {

        Sheet sheetFromFile = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheetFromFile == null) {
            throw new RRException("9000", "系统异常");
        }
        Integer count = 0;
        Row row;
        for (int r = 1; r <= sheetFromFile.getLastRowNum(); r++) {
            row = sheetFromFile.getRow(r);
            if (row == null) {
                continue;

            }
            //获取商户号
            String merchantCode=row.getCell(0).getStringCellValue().trim();

            TerTerminalInfo info = queryTerminalByMCode(merchantCode);


            if(info!=null){
                //已激活
                if(info.getIsActivation().intValue()==2){
                    continue;
                }

                //未报备跳过
                TerMerchantReport report = merchantService.queryMerchantBySn(info.getSn());
                if(report!=null && info.getIsReport().intValue()==2){
                    //线上，返现
                    if(info.getIsOnLine().intValue()==1){
                        //处理返现
                        //修改账户余额

                        agentInfoService.addAmount(info.getPurchaserId(), info.getReapAmount());
                        List<TranTransactionInfo> list = transactionInfoService.selectList(new EntityWrapper<TranTransactionInfo>().eq("sn", info.getSn()));
                        BigDecimal result = list.stream()
                                .filter(e -> e.getAmount() != null)
                                .map(TranTransactionInfo::getAmount)
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        //添加激活返现信息
                        String activIdSn = StringUtil.getDateString(6);
                        FlowActiv f = new FlowActiv();
                        f.setAgentId(info.getPurchaserId());
                        f.setCreateTime(new Date());
                        f.setSn(info.getSn());
                        f.setAmount(info.getReapAmount());
                        f.setPartAmount(result);
                        f.setActivDate(new Date());
                        f.setActivId(activIdSn);
                        flowActivService.insert(f);
                        //添加流水日志
                        FlowAccount account = new FlowAccount();
                        account.setCreateTime(new Date());
                        account.setAccountType(5);
                        account.setBelId(activIdSn);
                        account.setSupportType(2);
                        account.setAmount(info.getReapAmount());
                        account.setAgentId(info.getPurchaserId());
                        flowAccountService.insertFlowAccount(account);
                        count++;


                        //处理vip
                        FlowVipCashBack flowVipCashBack=new FlowVipCashBack();
                        flowVipCashBack.setAgentId(report.getAgentId());
                        flowVipCashBack.setCreateTime(new Date());
                        flowVipCashBack.setDoVipTime(new Date());
                        flowVipCashBack.setMoney(new BigDecimal("99.00"));
                        flowVipCashBack.setSn(info.getSn());
                        flowVipCashBack.setMerchantNo(merchantCode);
                        flowAccountService.addVipCashAccount(flowVipCashBack,8);
                        agentInfoService.addAmount(report.getAgentId(), new BigDecimal("99.00"));

                    }

                    activTerminal(info.getSn());

                }
            }
        }
        return count;
    }

    @Override
    public Integer uploadToViPXY(String fileName, MultipartFile file) {

        Sheet sheetFromFile = ExcelUtil.getSheetFromFile(fileName, file, 0);
        if (sheetFromFile == null) {
            throw new RRException("9000", "系统异常");
        }
        Integer count = 0;
        Row row;
        for (int r = 1; r <= sheetFromFile.getLastRowNum(); r++) {
            row = sheetFromFile.getRow(r);
            if (row == null) {
                continue;

            }
            //获取商户号
            String merchantCode=row.getCell(0).getStringCellValue().trim();

            TerTerminalInfo info = queryTerminalByMCode(merchantCode);

            if(info!=null){
                //未激活跳过
                if(info.getIsActivation().intValue()==1){
                    continue;
                }

                //未报备跳过
                TerMerchantReport report = merchantService.queryMerchantBySn(info.getSn());
                if(report!=null && info.getIsReport().intValue()==2){
                    //线上，返现
                    if(info.getIsOnLine().intValue()==1){
                        //处理返现
                        count++;

                        //处理vip
                        FlowVipCashBack flowVipCashBack=new FlowVipCashBack();
                        flowVipCashBack.setAgentId(report.getAgentId());
                        flowVipCashBack.setCreateTime(new Date());
                        flowVipCashBack.setDoVipTime(new Date());
                        flowVipCashBack.setMoney(new BigDecimal("79.00"));
                        flowVipCashBack.setSn(info.getSn());
                        flowVipCashBack.setMerchantNo(merchantCode);
                        flowAccountService.addVipCashAccount(flowVipCashBack,8);
                        agentInfoService.addAmount(report.getAgentId(), new BigDecimal("79.00"));

                    }
                }
            }
        }
        return count;
    }


}
